package cn.ycl.config;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 解决openfeign远程调用接口时，请求头数据丢失问题
 *
 * @author yuanchangliang
 * @date 2022-06-30 9:38
 */
@Configuration
public class OpenFeignConfig {

    @Bean
    public RequestInterceptor requestInterceptor(){
        //这里不推荐lambda表达式，可读性大降
        return new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate template) {
                //获取老请求
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                if(Objects.isNull(requestAttributes)){
                    return;
                }
                HttpServletRequest request = requestAttributes.getRequest();
                String cookie = request.getHeader("Cookie");
                String token = request.getHeader("token");
                //给新请求同步
                template.header("Cookie",cookie);
                template.header("token",token);
            }
        };
    }
}